import time
from hashlib import md5
import random
import json
import requests
import logging
from odoo import fields, models
from odoo.exceptions import UserError

LANGUAGE_MAPPING = [('zh', 'chinese'), ('en', 'english'), ('spa', 'spanish'), ('cat', 'catalan'), ('fra', 'french')]

logger = logging.getLogger(__name__)


class RpTranslationFillLanguageTran(models.TransientModel):
    _name = 'rp.translation.fill.language.tran'
    _description = '填充翻译'

    base_language = fields.Selection(string='基语言', selection=LANGUAGE_MAPPING)
    to_fill_language = fields.Selection(string='填充语言', selection=LANGUAGE_MAPPING)

    def get_translation(self, query, from_lang, to_lang):
        api_id = '20240625002084698'
        secret_key = 'LbjRXyh96BvW_quHoV2Z'
        endpoint = 'http://api.fanyi.baidu.com'
        path = '/api/trans/vip/translate'
        url = endpoint + path

        def make_md5(s, encoding='utf-8'):
            return md5(s.encode(encoding)).hexdigest()

        salt = random.randint(32768, 65536)
        sign = make_md5(api_id + query + str(salt) + secret_key)
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        payload = {'appid': api_id, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}
        # 发送请求，返回数据，如果出错采用重试【默认四次】
        result_dict = None
        result = None
        for count in range(4):
            try:
                r = requests.post(url, params=payload, headers=headers)
                result = r.json()
                result_obj = json.dumps(result, indent=4, ensure_ascii=False)
                result_dict = json.loads(result_obj)
                result = result_dict.get('trans_result')[0].get('dst')
                logger.info('(%s)翻译成功，翻译结果：%s' % (query, result))
                break
            except Exception:
                logger.warning(f'({query})翻译失败【{count + 1}次失败】')
        if result_dict.get('error_code') or result_dict.get('error_msg'):
            return result
        return result

    def fill_language(self):
        """
        填充语言
        """

        def get_field(key):
            for record, value in LANGUAGE_MAPPING:
                if record.strip() == key.strip():
                    return value

        if not self.to_fill_language:
            raise UserError('请选择要填充的语言!')
        if not self.base_language:
            raise UserError('请选择基语言！')
        if self.to_fill_language == self.base_language:
            raise UserError('基语言和目标语言不能相同！')

        translation_records = self.env['rp.translation.table'].search([])
        from_list = translation_records.filtered(lambda r: eval('r.' + get_field(self.base_language)) and eval('r.' + get_field(self.base_language)).strip() != '').mapped(lambda r: eval('r.' + get_field(self.base_language)))
        if len(from_list) != len(translation_records.ids):
            raise UserError(f'存在部分记录不存在{get_field(self.base_language)}值，无法进行填充!')
        for record in translation_records:
            try:
                query = eval('record.' + get_field(self.base_language)).strip()
            except Exception:
                logger.warning('出错')
                continue
            translation_value = self.get_translation(query=query, from_lang=self.base_language, to_lang=self.to_fill_language)
            field_name = get_field(self.to_fill_language)
            if field_name and translation_value:
                record.write({field_name: translation_value})
